package com.engine.workflow.autolink.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-05-10
 * @Description: 调用自定义流程接口
 * @ModifyLog:
 **/

public class WeaWorkflowWeb extends BaseBean {
    /**
     * @Description: 流程创建
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/7/17
     */
    @POST
    @Path("/doCreateRequest")
    @Produces({MediaType.TEXT_PLAIN})
    public String doCreateRequest(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WfUtil wfUtil = new WfUtil();

        String workflowId = Util.null2String(request.getParameter("workflowId"));
        String requestName = Util.null2String(request.getParameter("requestName"));
        String mainData = Util.null2String(request.getParameter("mainData"));
        String detailData = Util.null2String(request.getParameter("detailData"));
        String isnextFlow = Util.null2String(request.getParameter("isnextFlow"));
        String rASUserid = Util.null2String(request.getHeader("userid"));
        String rASToken = Util.null2String(request.getHeader("token"));
        try {
            Map<String, Object> returnParamsMap = wfUtil.checkReqParams(workflowId, requestName, mainData, isnextFlow);
            String paramsCode = Util.null2String(returnParamsMap.get("code"));
            writeLog(">>>>>doCreateRequest>>>paramsCode=" + paramsCode);
            if (!"SUCCESS".equals(paramsCode)) {
                apidatas = returnParamsMap;
            } else {
                Map<String, Object> returnHeadParamsMap = wfUtil.checkHeadParams(rASToken, rASUserid);
                String headparamsCode = Util.null2String(returnHeadParamsMap.get("code"));
                writeLog(">>>>>doCreateRequest>>>headparamsCode=" + headparamsCode);
                if (!"SUCCESS".equals(headparamsCode)) {
                    apidatas = returnHeadParamsMap;
                } else {
                    String userId = Util.null2String(returnHeadParamsMap.get("message"));
                    JSONArray mainDatalist = JSONArray.parseArray(mainData);
                    Map<String, Object> mainMap = new HashMap<String, Object>();
                    for (int i = 0; i < mainDatalist.size(); i++) {
                        JSONObject mainFields = mainDatalist.getJSONObject(i);
                        String fieldName = Util.null2String(mainFields.getString("fieldName"));
                        String fieldValue = Util.null2String(mainFields.getString("fieldValue"));
                        mainMap.put(fieldName, fieldValue);
                    }
                    String newRequestid = wfUtil.WorkflowCreateByRequestMap(userId, workflowId, requestName, isnextFlow, mainMap);
                    writeLog(">>>>>doCreateRequest>>>newRequestid=" + newRequestid);
                    if (Util.getIntValue(newRequestid) > 0) {
                        if (!"".equals(detailData)) {
                            JSONArray detailDatalist = JSONArray.parseArray(detailData);
                            String mainid = Util.null2String(wfUtil.getIdByRequestId(workflowId, newRequestid));
                            int dtlTableSumCount = detailDatalist.size();
                            int dtlTableSuccCount = 0;
                            for (int i = 0; i < detailDatalist.size(); i++) {
                                JSONObject detailDatas = detailDatalist.getJSONObject(i);
                                String dtltableName = Util.null2String(detailDatas.getString("tableDBName"));
                                if (!"".equals(dtltableName)) {
                                    writeLog(">>>>>doUpdateRequest>>>detailData>>>>dtltableName=" + dtltableName);
                                    String tableRecords = Util.null2String(detailDatas.getString("workflowRequestTableRecords"));
                                    if (!"".equals(tableRecords)) {
                                        JSONArray recordslist = JSONArray.parseArray(tableRecords);
                                        int sumCount = recordslist.size();
                                        int succCount = 0;
                                        for (int j = 0; j < recordslist.size(); j++) {
                                            Map<String, Object> detailMap = new HashMap<String, Object>();
                                            JSONObject records = recordslist.getJSONObject(j);
                                            String recordOrder = Util.null2String(records.getString("recordOrder"));
                                            writeLog("detailData>>>>recordOrder=" + recordOrder);
                                            String tableFields = Util.null2String(records.getString("workflowRequestTableFields"));
                                            if (!"".equals(tableFields)) {
                                                JSONArray tableFieldslist = JSONArray.parseArray(tableFields);
                                                for (int k = 0; k < tableFieldslist.size(); k++) {
                                                    JSONObject detailFields = tableFieldslist.getJSONObject(k);
                                                    String fieldName = Util.null2String(detailFields.getString("fieldName"));
                                                    String fieldValue = Util.null2String(detailFields.getString("fieldValue"));
                                                    detailMap.put(fieldName, fieldValue);
                                                }
                                                detailMap.put("mainid", mainid);
                                                boolean isDtlUpdate = wfUtil.updateDetailData(dtltableName, detailMap);
                                                writeLog(">>>>>doUpdateRequest>>>isDtlUpdate=" + isDtlUpdate);
                                                if (isDtlUpdate) {
                                                    succCount++;
                                                }
                                            }
                                        }
                                        if (succCount == sumCount) {
                                            dtlTableSuccCount++;
                                        }
                                        writeLog(">>>>>doUpdateRequest>>>succCount=" + succCount + ",sumCount=" + sumCount);
                                    }
                                }
                            }
                            writeLog(">>>>>doUpdateRequest>>>dtlTableSuccCount=" + dtlTableSuccCount + ",dtlTableSumCount=" + dtlTableSumCount);
                            if (dtlTableSumCount == dtlTableSuccCount) {
                                apidatas.put("code", "SUCCESS");
                                JSONObject datajson = new JSONObject();
                                datajson.put("requestid", newRequestid);
                                apidatas.put("data", datajson);
                                apidatas.put("message", "流程创建成功");
                            } else {
                                wfUtil.deleteWorkflow(Util.getIntValue(newRequestid), Util.getIntValue(userId));
                                apidatas.put("code", "PARAM_ERROR");
                                apidatas.put("data", "");
                                apidatas.put("message", "detailData参数错误，明细表更新失败");
                            }
                        } else {
                            apidatas.put("code", "SUCCESS");
                            JSONObject datajson = new JSONObject();
                            datajson.put("requestid", newRequestid);
                            apidatas.put("data", datajson);
                            apidatas.put("message", "流程创建成功");
                        }
                    } else {
                        apidatas.put("code", "PARAM_ERROR");
                        JSONObject dataJson = new JSONObject();
                        dataJson.put("requestid", newRequestid);
                        apidatas.put("data", dataJson);
                        apidatas.put("message", "流程创建失败");
                    }
                    writeLog(">>>>>doCreateRequest>>>apidatas=" + apidatas.toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("code", "SYSTEM_INNER_ERROR");
            apidatas.put("data", "");
            apidatas.put("message", "程序内部异常");
        }

        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 流程控制节点流向
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/7/17
     */
    @POST
    @Path("/doForwardRequest")
    @Produces({MediaType.TEXT_PLAIN})
    public String doForwardRequest(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WfUtil wfUtil = new WfUtil();
        String requestId = Util.null2String(request.getParameter("requestId"));
        String workflowId = Util.null2String(request.getParameter("workflowId"));
        String isLeave = Util.null2String(request.getParameter("isLeave"));
        String rASUserid = Util.null2String(request.getHeader("userid"));
        String rASToken = Util.null2String(request.getHeader("token"));
        try {
            Map<String, Object> returnParamsMap = wfUtil.checkReqParams1(requestId, workflowId, isLeave);
            String paramsCode = Util.null2String(returnParamsMap.get("code"));
            writeLog(">>>>>doForwardRequest>>>paramsCode=" + paramsCode);
            if (!"SUCCESS".equals(paramsCode)) {
                apidatas = returnParamsMap;
            } else {
                Map<String, Object> returnHeadParamsMap = wfUtil.checkHeadParams(rASToken, rASUserid);
                String headparamsCode = Util.null2String(returnHeadParamsMap.get("code"));
                writeLog(">>>>>doForwardRequest>>>headparamsCode=" + headparamsCode);
                if (!"SUCCESS".equals(headparamsCode)) {
                    apidatas = returnHeadParamsMap;
                } else {
                    if ("0".equals(isLeave)) {
                        String userId = Util.null2String(returnHeadParamsMap.get("message"));
                        String resultStr = wfUtil.submitWorkflow(Util.getIntValue(requestId), Util.getIntValue(userId));
                        writeLog(">>>>>doForwardRequest>>>resultStr=" + resultStr);
                        if ("success".equals(resultStr)) {
                            apidatas.put("code", "SUCCESS");
                            JSONObject dataJson = new JSONObject();
                            dataJson.put("status", resultStr);
                            apidatas.put("data", dataJson);
                            apidatas.put("message", "流程提交成功");
                        } else {
                            apidatas.put("code", "NO_PERMISSION");
                            JSONObject dataJson = new JSONObject();
                            dataJson.put("status", resultStr);
                            apidatas.put("data", dataJson);
                            apidatas.put("message", "流程提交失败");
                        }
                    } else {
                        apidatas.put("code", "SUCCESS");
                        apidatas.put("data", "");
                        apidatas.put("message", "流程无需操作");
                    }

                    writeLog(">>>>>doForwardRequest>>>apidatas=" + apidatas.toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("code", "SYSTEM_INNER_ERROR");
            apidatas.put("data", "");
            apidatas.put("message", "程序内部异常");
        }

        return JSONObject.toJSONString(apidatas);
    }

}
